package controllers.adminC

import java.io.File

import dao._
import implicits.Implicits._
import javax.inject.Inject
import models.Tables.DataRow
import play.api.libs.json.Json
import play.api.mvc._
import tool.{FileTool, FormTool, Tool}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * Created by yz on 21/7/2020
 */
class DataController @Inject()(cc: ControllerComponents)(
  implicit val userDao: UserDao,
  implicit val accountDao: AccountDao,
  implicit val modeDao: ModeDao,
  implicit val dataDao: DataDao
) extends AbstractController(cc) {

  def addByFileBefore = Action { implicit request =>
    Ok(views.html.admin.data.addByFile())
  }

  def addByFile = Action.async(parse.multipartFormData) { request =>
    val file = request.body.file("file").get
    val tmpDir = Tool.createTempDirectory("tmpDir")
    val tmpXlsxFile = new File(tmpDir, "tmp.xlsx")
    file.ref.moveTo(tmpXlsxFile, true)
    val myMessage = FileTool.fileCheck(tmpXlsxFile).toMyMessage
    if (!myMessage.valid) {
      Tool.deleteDirectory(tmpDir)
      Future.successful(Ok(Json.obj("message" -> myMessage.message, "valid" -> false)))
    } else {
      val lines = tmpXlsxFile.xlsxLines()
      val headers = lines.head
      val rows = lines.lineMapNoLower.map { map =>
        val otherMap = map -- List("Tumor_Sample_Barcode", "Tumor_Sample_Name", "OncoTree_Code", "Gene.refGene")
        DataRow(id = 0, barcode = map("Tumor_Sample_Barcode"), sampleName = map("Tumor_Sample_Name"),
          treeCode = map("OncoTree_Code"), refGene = map("Gene.refGene"), otherInfo = otherMap
        )
      }
      dataDao.insertOrUpdates(rows).map { x =>
        Tool.deleteDirectory(tmpDir)
        Ok(Json.obj("valid" -> true))
      }
    }
  }

  def manageBefore = Action { implicit request =>
    Ok(views.html.admin.data.manage())
  }

  def deletes = Action.async { implicit request =>
    val data = FormTool.idsForm.bindFromRequest().get
    dataDao.deleteAll(data.ids).map { _ =>
      Ok("success!")
    }
  }

  def deleteById = Action.async { implicit request =>
    val data = FormTool.idForm.bindFromRequest().get
    dataDao.delete(data.id).map { x =>
      Ok("success!")
    }
  }


}
